{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用动态规划法求解 0-1 背包问题.\n",
    "使用动态规划求解 0-1 背包问题. 定义动态规划：\n",
    "1. 阶段：放第几个物品 \n",
    "2. 状态：当前背包容量\n",
    "3. 动作：是否放入物品.\n",
    "4. 价值函数：目前背包的价值.\n",
    "5. 贝尔曼最优方程: $V^*(s_t) = \\max_a (r_i(s,a) + V^*(s_{t+1}))$ \n",
    "\n",
    "递归式:\n",
    "\\begin{align*}\n",
    "V(i,j) & = \n",
    "\\begin{cases}\n",
    "    V(i+1,j) \\qquad w_i > j \\\\\n",
    "    \\max(V(i+1,j-w_i) + v_i,V(i+1,j)) \\qquad w_i < j\n",
    "\\end{cases}\n",
    "\\end{align*}\n",
    "边界条件:\n",
    "\\begin{align*}\n",
    "V(n,j) & = \n",
    "\\begin{cases}\n",
    "    0 \\qquad w_n > j \\\\\n",
    "    v_n \\qquad w_i < j\n",
    "\\end{cases}\n",
    "\\end{align*}\n",
    "\n",
    "时间复杂度: \n",
    "\\begin{gather*}\n",
    "\\begin{cases}\n",
    "    \\Omega(nc) \\qquad c < 2^n \\\\\n",
    "    \\Omega(n2^n) \\qquad c > 2^n\n",
    "\\end{cases}\n",
    "\\end{gather*}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 基本设置\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15 70 [4, 13, 2, 18, 3, 3, 4, 16, 8, 17, 5, 1, 20, 2, 14] [21, 1, 3, 11, 13, 16, 16, 20, 21, 11, 15, 7, 10, 3, 19]\n"
     ]
    }
   ],
   "source": [
    "# 数据读取\n",
    "import re\n",
    "def LoadData(path):\n",
    "    '''\n",
    "    数据读取。\n",
    "    Input:\n",
    "    - path: 数据路径.\n",
    "    \n",
    "    Return:\n",
    "    - cache: a list contains (n,c,w,v)\n",
    "    '''\n",
    "    cache = []\n",
    "    with open(path,'r') as f:  \n",
    "         for i in range(4):\n",
    "            x = re.findall(r'\\d+',f.readline())\n",
    "            x = [int(i) for i in x]\n",
    "            cache.append(x)\n",
    "    return cache\n",
    "    \n",
    "path = 'test3.txt'\n",
    "n,c,w,v = LoadData(path)\n",
    "n = n[0]\n",
    "c = c[0]\n",
    "print(n,c,w,v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [],
   "source": [
    "def Bellman(stage,state,w,v,value,n):\n",
    "    '''\n",
    "    贝尔曼最优方程.\n",
    "    Input:\n",
    "    - stage: stage.\n",
    "    - state: state.\n",
    "    - w: cost function.\n",
    "    - v: reward function\n",
    "    - value: value function.\n",
    "    - n: num of stage.\n",
    "    \n",
    "    ''' \n",
    "    if stage == (n-1):\n",
    "        # 最后阶段.\n",
    "        if state - w[stage] >= 0:\n",
    "            value[(stage,state)] = v[stage]\n",
    "            state_n = state - w[stage]\n",
    "        else:\n",
    "            value[(stage,state)] = 0\n",
    "            state_n = state\n",
    "    else:\n",
    "        if state - w[stage] < 0:\n",
    "            value[(stage,state)] = value[(stage+1,state)] if ((stage+1,state) in value) else Bellman(stage+1,state,w,v,value,n)[0]\n",
    "            state_n = state\n",
    "        else:\n",
    "            value1 = value[(stage+1,state)] if ((stage+1,state) in value) else Bellman(stage+1,state,w,v,value,n)[0]\n",
    "            add = value[(stage+1,state-w[stage])] if ((stage+1,state-w[stage]) in value) else Bellman(stage+1,state-w[stage],w,v,value,n)[0]\n",
    "            value2 = v[stage] + add\n",
    "            if value1 > value2:\n",
    "                value[(stage,state)] = value1\n",
    "                state_n = state\n",
    "            else:\n",
    "                value[(stage,state)] = value2\n",
    "                state_n = state - w[stage]\n",
    "    return value[(stage,state)],state_n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "154\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "154"
      ]
     },
     "execution_count": 79,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def DP(n,c,w,v):\n",
    "    '''\n",
    "    使用动态规划求解 0-1 背包问题.\n",
    "    Input:\n",
    "    - n: 物品数量.\n",
    "    - c: 背包容量.\n",
    "    - w: 物品重量.\n",
    "    - v: 物品价值.\n",
    "    \n",
    "    Return:\n",
    "    - values: 最优价值.\n",
    "    '''\n",
    "    # 定义\n",
    "    value = {} # 价值函数, 由二元组 <stage, state> 表征\n",
    "    state = c # 状态\n",
    "    values,_ = Bellman(0,state,w,v,value,n)\n",
    "    print(values)\n",
    "    return values\n",
    "DP(n,c,w,v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "torch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
